package com.michale.framework.security.context;

import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.common.utils.security.SecurityUtils;
import com.michale.framework.security.service.TokenService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * @author Michale
 * @apiNote token过滤器 验证token有效性
 */
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private TokenService tokenService;

    /**
     * 与 {@code doFilter} 的协定相同，但保证在单个请求线程中每个请求只调用一次
     *
     * @param request     request请求域
     * @param response    response相应
     * @param filterChain 过滤器链
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求中获取token并且解析token获取UUID,通过UUID从缓存中获取用户信息
        LoginUserDetail loginUser = tokenService.getLoginUser(request);
        //判断Token中存在用户并且Authentication中不存在用户信息
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())){
            //刷新token过期时间并且把用户信息进行缓存
            tokenService.verifyToken(loginUser);
            //获取授予用户的权限
            Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
            //创建用户名密码身份验证令牌
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, authorities);
            //网络身份验证详细信息
            WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetailsSource().buildDetails(request);
            authenticationToken.setDetails(webAuthenticationDetails);
            //把用户名密码身份验证令牌存入安全上下文中
            SecurityUtils.setAuthentication(authenticationToken);
            //最后把登录成功的用户的token进行缓存
            redisUtils.setCacheObject(RedisCacheConstant.LOGIN_KEY + SecurityUtils.getLoginUser().getUsername(), SecurityUtils.getLoginUser().getToken(), 60 * 60, TimeUnit.MINUTES);
        }
        filterChain.doFilter(request, response);
    }
}